import axios, { AxiosRequestConfig } from 'axios'

// 请求操作
export function request(
  configs: AxiosRequestConfig<any>,
  ignoreSuccess = false
) {
  const { url, ...restConfigs } = configs
  // 如果当前的端口为 3000，则为本地调试
  const isLocal = window.location.port === '3000'
  let handledUrl = url
  if (isLocal) {
    handledUrl = `http://localhost:8888${handledUrl}`
  }
  return new Promise((resolve) => {
    axios({
      url: handledUrl,
      ...restConfigs
    })
      .then((res) => {
        if (ignoreSuccess) {
          resolve(res.data)
          return
        }
        if (res.data.success) {
          resolve(res.data)
        } else {
          resolve(null)
        }
      })
      .catch(() => {
        console.error('服务器异常')
        resolve(null)
      })
  })
}
